package com.feishi.core.lucene;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-4-13 13:50
 **/
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.FSDirectory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;

/**
 * Index all text files under a directory.
 * <p>
 * This is a command-line application demonstrating simple Lucene indexing.
 * Run it with no command-line arguments for usage information.
 */public class IndexFiles {
    private IndexFiles() {
    }

    public static void main(String[] args) {
        //在运行是要添加参数如：-docs （你文件的路径）
        String projectPath=IndexFiles.class.getResource("/").getPath();
        //索引文件输出地址
        String indexPath = projectPath+"index";
        //要检索的文件或者文件夹地址
        String docsPathStr =projectPath+ "Test.txt";
        boolean create = true;



        /**
         * nio path设置
         * */
        Path docsPath = Paths.get(docsPathStr, new String[0]);
        //读写权限判定
//        if(!Files.isReadable(docsPath)) {
//            System.out.println("Document directory \'" + docsPath.toAbsolutePath() + "\' does not exist or is not readable, please check the path");
//            System.exit(1);
//        }

        Date start = new Date();

        try {
            System.out.println("Indexing to directory \'" + indexPath + "\'...");
            //打开文件路径
            FSDirectory directory = FSDirectory.open(Paths.get(indexPath, new String[0]));
            //基本分词器创建
            StandardAnalyzer analyzer = new StandardAnalyzer();
            //索引写配置
            IndexWriterConfig indexWriterConfig = new IndexWriterConfig(analyzer);
            if(create) {
                indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
            } else {
                indexWriterConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
            }
            //索引写入工具
            IndexWriter writer = new IndexWriter(directory, indexWriterConfig);
            indexDocs(writer, docsPath);
            //关闭写入工具
            writer.close();
            Date end = new Date();
            System.out.println(end.getTime() - start.getTime() + " total milliseconds");
        } catch (IOException var12) {
            System.out.println(" caught a " + var12.getClass() + "\n with message: " + var12.getMessage());
        }

    }

    static void indexDocs(final IndexWriter writer, Path path) throws IOException {
        /**
         * 文件夹判定
         * 如果为文件夹
         * 遍历整个文件夹
         * 否则直接写入文件
         * */
        if(Files.isDirectory(path, new LinkOption[0])) {
            Files.walkFileTree(path, new SimpleFileVisitor() {
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    try {
                        IndexFiles.indexDoc(writer, file, attrs.lastModifiedTime().toMillis());
                    } catch (IOException var4) {
                        ;
                    }

                    return FileVisitResult.CONTINUE;
                }
            });
        } else {
            indexDoc(writer, path, Files.getLastModifiedTime(path, new LinkOption[0]).toMillis());
        }

    }
    /**
     * 单个文件写入索引
     * */
    static void indexDoc(IndexWriter writer, Path file, long lastModified) throws IOException {
        InputStream stream = Files.newInputStream(file, new OpenOption[0]);
        Throwable throwable = null;

        try {
            Document doc = new Document();
            StringField pathField = new StringField("path", file.toString(), Field.Store.YES);
            doc.add(pathField);
            doc.add(new LongPoint("modified", new long[]{lastModified}));
            doc.add(new TextField("contents", new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))));

            if(writer.getConfig().getOpenMode() == IndexWriterConfig.OpenMode.CREATE) {
                System.out.println("adding " + file);
                writer.addDocument(doc);
            } else {
                System.out.println("updating " + file);
                writer.updateDocument(new Term("path", file.toString()), doc);
            }
        } catch (Throwable e) {
            /**
             * 将异常纳入逻辑处理中
             * */
            throwable = e;

            try {
                throw e;
            } catch (Throwable ee) {
                ee.printStackTrace();
            }
        } finally {
            if(stream != null) {
                if(throwable != null) {
                    try {
                        stream.close();
                    } catch (Throwable var14) {
                        throwable.addSuppressed(var14);
                    }
                } else {
                    stream.close();
                }
            }

        }

    }
}